from MBlog_backend.custom_response import custom_response
from tag.models import tag
from article.models import articles as art_model
from django.db.models import F, Count
import json


# Create your views here.

def list(request):
    tag_list = tag.objects.all().annotate(tagName=F('tag_name'), articleNum=Count('articles__id'))
    tag_list = tag_list.values('id', 'tagName', 'avatar', 'articleNum')
    tag_list = [i for i in tag_list]
    resp = custom_response()
    if not tag_list:
        resp.set_code('3001')
        resp.set_message('未找到标签！')
    else:
        resp.data_update(tag_list)
    return resp.response


def hot(request):
    tag_ojbs = tag.objects.all().annotate(tagName=F('tag_name')).values('id', 'tagName').order_by('-create_time')[:4]
    tag_list = [x for x in tag_ojbs]
    resp = custom_response()
    resp.data_update(tag_list)
    return resp.response


def all(request):
    tag_list = tag.objects.all().annotate(tagName=F('tag_name'), articleNum=Count('articles__id'))
    tag_list = tag_list.values('id', 'tagName', 'avatar', 'articleNum')
    tag_list = [i for i in tag_list]
    resp = custom_response()
    if not tag_list:
        resp.set_code('3001')
        resp.set_message('未找到标签！')
    else:
        resp.data_update(tag_list)
    return resp.response


def detail(request):
    body = json.loads(request.body)
    id = body.get('id')
    tag_obj = tag.objects.filter(id__exact=id).values('id', 'tag_name', 'article_tag__article_id')
    tag_obj = tag_obj.annotate(articleNum=Count('article_tag__article_id'), tagName=F('tag_name'))
    tag_obj = tag_obj.values('id', 'tagName', 'articleNum').first()
    resp = custom_response()
    resp.data_update(tag_obj)
    return resp.response


# def test():
#     tag_obj = tag.objects.filter(id__exact=3).values('id', 'tag_name', 'article_tag__article_id')
#     tag_obj = tag_obj.annotate(articleNum=Count('article_tag__article_id'), tagName=F('tag_name'))
#     tag_obj = tag_obj.values('id', 'tagName', 'articleNum').first()
